package com.wcs.exam.common.llm.impl;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.wcs.exam.common.base.BaseSse;
import com.wcs.exam.common.constant.BaseConstant;
import com.wcs.exam.common.llm.LlmBaseResp;
import com.wcs.exam.common.llm.LlmFace;
import com.wcs.exam.common.llm.impl.bean.Message;
import com.wcs.exam.common.llm.impl.bean.ModelBean;
import okhttp3.Headers;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;

/**
 * <a href="https://bigmodel.cn/dev/howuse/introduction">接口地址</a>
 */
@Component(value = BaseConstant.ModelType.ZHIPU)
public class ZhiPuImpl implements LlmFace {

    private static final String API_CHAT_URL = "https://open.bigmodel.cn/api/paas/v4/chat/completions";

    @Override
    public SseEmitter chat(LlmFace llmFace, ModelBean modelBean, List<Message> messages) {
        Headers headers = new Headers.Builder().add("Authorization", "Bearer " + modelBean.getApiKey()).build();
        String requestBody = new JSONObject().putOpt("model", modelBean.getModel()).putOpt("messages", messages).putOpt("stream", true).toString();
        return BaseSse.stream(llmFace, API_CHAT_URL, headers, requestBody);
    }

    @Override
    public LlmBaseResp http(ModelBean modelBean, List<Message> messages) {
        return BaseSse.http(API_CHAT_URL, modelBean.getApiKey(), modelBean.getModel(), messages);
    }

    @Override
    public String chatHandle(String content) {
        Object val = JSONPath.eval(content, "$.choices[0].delta.content");
        return String.valueOf(val);
    }

}
